//
//  SubDetailViewController.m
//  ZAKER
//
//  Created by dllo on 15/8/24.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "SubDetailViewController.h"



@interface SubDetailViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UITableViewDelegate>

{
    
    NSInteger _itemNum; // 记录tableView所在的item号
    
}

@property (nonatomic, retain) NSMutableArray *myArray;
@property (nonatomic, retain) NSMutableArray *brray;
@property (nonatomic, retain) NSMutableArray *urlArr; //  存放webView网址
@property (nonatomic, retain) UICollectionView *collection;
@property (nonatomic, retain) NSString *refreshStr; // 刷新界面时候, 他网址传到自定义的collectionViewCell中.
@property (nonatomic, retain) MBProgressHUD *mb;

@end

@implementation SubDetailViewController
-(void)dealloc
{
    
    [_labelStr release];
    [_brray release];
    [_urlArr release];
    [_myArray release];
    [_collection release];
    [_refreshStr release];
    [_mb release];
    
    [super dealloc];
    
}
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
        
        self.myArray = [NSMutableArray array];
        self.brray = [NSMutableArray array];
        self.urlArr = [NSMutableArray array];
        
    }
    
    return self;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(150 * myWidth, 10 * myHeight, 75 * myWidth, 40 * myHeight)];
    label.text = self.labelStr;
    self.navigationItem.titleView = label;
    [label release];
    
    UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
    _mb = [[MBProgressHUD alloc] initWithView:window];
    [window addSubview:_mb];
    _mb.labelText = @"正在加载";
    [_mb show:YES];
    [self myConnection];
    
     // 十秒后,如果数据还没请求出来, 就停止
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)10 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        if (_mb != nil) {
            [_mb removeFromSuperview];
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"数据加载失败" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alert  show];
            [alert release];
        
        }
    });
    
    [self createCollection];
    [self instrustButton];
   
}

#pragma mark - 创建collectionView以及实现协议方法

-(void)createCollection
{
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(self.view.frame.size.width, 554 * myHeight);
    layout.minimumInteritemSpacing = 1;
    layout.minimumLineSpacing = 1;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    
    self.collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, -30 * myHeight, self.view.frame.size.width, self.view.frame.size.height) collectionViewLayout:layout];
    _collection.backgroundColor = [UIColor whiteColor];
    _collection.delegate = self;
    _collection.dataSource = self;
    _collection.pagingEnabled = YES;
    [_collection registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:@"reuse" ];
    [self.view addSubview:_collection];
    [layout release];
    [_collection release];
    
    
}

-(NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    if (_myArray.count % 3 == 0) {
        
        return _myArray.count / 3 ;
        
    } else {
        
        return _myArray.count / 3 + 1;
        
    }
    
    return 0;
    
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.modelArray = _myArray;
    
    // 第一步：所以在每个Item的tableView所在的类建立一个属性numItem用来区分当前tableView在collectionView的哪个Item
    cell.numItem = indexPath.item;
    _itemNum = indexPath.item;
    
    [cell createTableView];
    cell.tableView.delegate = self;
    
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    // 获取到点击的是哪个item的那个row 然后从数组中取出model
    NSInteger numberNum = _itemNum * 3 + indexPath.row;
    
    //    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    if ([_myArray count] > numberNum) {
        
        CellModel *model = _myArray[numberNum];
        WedViewController *web  = [[WedViewController alloc] init];
        web.model = model;
        [self.navigationController pushViewController:web animated:YES];
        [web release];
        
    }
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
    NSInteger  num = self.collection.contentOffset.x /self.collection.frame.size.width;
    _itemNum = num;
    
}

#pragma mark - 提示左右滑动的透明button

-(void)instrustButton
{
    // 第一次进入提示, 以后不需要提示
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    if ([user objectForKey:@"instruct"] == nil) {
        [user setValue:@"i" forKey:@"instruct"];
        
        UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        button.alpha = 0.85;
        button.backgroundColor = [UIColor grayColor];
        
        UIWindow *window = [UIApplication sharedApplication].windows.firstObject;
        [window addSubview:button];
        [button setImage:[UIImage imageNamed:@"button2.jpg"] forState:UIControlStateNormal];
        
        // 三秒后消失
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [button removeFromSuperview];
        });
        
        [button addTarget:self action:@selector(instrusAction:) forControlEvents:UIControlEventTouchUpInside];
        [button release];
        
    }
}
#pragma mark - 点击之后, 从window上移除

-(void)instrusAction:(UIButton *)button
{
    
    [button removeFromSuperview];
    
}


// 根据button的tag值, 判断点击的是那个button
-(void)sendTag:(NSInteger)mytag labelArray:(NSMutableArray *)labelArray
{
    
    self.myTag = mytag;
    self.labelStr = [labelArray objectAtIndex:mytag - 1];
    
}
#pragma  mark - 数据解析

-(void)myConnection
{
    NSInteger tag = self.myTag;
    
    // 拼接id, 进入各自对应的webView
    NSArray *arr = [NSArray arrayWithObjects:@"203",@"117", @"202", @"183", @"293", @"142",@"138", @"123", @"313",nil];
    self.refreshStr = [NSString stringWithFormat:@"http://api.m.jiemian.com/article/cate/%@.json?page=1&version=2.1.1&page=1", [arr objectAtIndex:tag -1]];
    
    [MyAFNetworking GetWithURL:_refreshStr dic:nil data:^(id responsder) {
        
        NSDictionary *dictionary = [responsder objectForKey:@"result"];
        NSArray *array = [dictionary objectForKey:@"rst"];
        
        for (int i = 0; i < [array count]; i++) {
            
            CellModel *model = [[CellModel alloc]init];
            [model setValuesForKeysWithDictionary:[array objectAtIndex:i]];
            [self.myArray addObject:model];
            [model release];
            
        }
        
        [self.collection reloadData];
        
        [_mb hide:YES];
        _mb = nil;
        
    }];
}

- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];
    
}


@end
